package com.joizhang.reactor.app;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

/**
 * @author joizhang
 */
public class LoggingClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggingClient.class);

    public static void main(String[] args) {
        try (Socket socket = new Socket(InetAddress.getLocalHost(), 6666)) {
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(outputStream);
            sendLogRequests(writer, socket.getInputStream());
        } catch (IOException e) {
            LOGGER.error("error sending requests", e);
        }
    }

    private static void sendLogRequests(PrintWriter writer, InputStream inputStream) throws IOException {
        for (int i = 0; i < 4; i++) {
            writer.println("Test client - Log request: " + i);
            writer.flush();

            byte[] data = new byte[1024];
            int read = inputStream.read(data,0,data.length);
            if (read == 0) {
                LOGGER.info("Read zero bytes");
            } else {
                LOGGER.info(new String(data,0,read));
            }
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                LOGGER.error(e.getMessage());
            }
        }
    }

}
